package com.example.myapplication;

import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private UserAdapter userAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化 RecyclerView
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        // 获取数据并加载到 RecyclerView
        fetchUserData();
    }

    private void fetchUserData() {
        // 创建 OkHttpClient 实例
        OkHttpClient client = new OkHttpClient();

        // 请求 URL
        String url = "https://jsonplaceholder.typicode.com/users";

        // 创建 Request 对象
        Request request = new Request.Builder().url(url).build();

        // 发送异步请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() ->
                        Toast.makeText(MainActivity.this,
                                "请求失败: " + e.getMessage(),
                                Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    // 获取 JSON 响应体
                    String jsonResponse = response.body().string();

                    // 使用 GSON 解析 JSON
                    Gson gson = new Gson();
                    Type listType = new TypeToken<List<User>>(){}.getType();
                    List<User> userList = gson.fromJson(jsonResponse, listType);

                    // 更新 UI
                    runOnUiThread(() -> {
                        userAdapter = new UserAdapter(userList);
                        recyclerView.setAdapter(userAdapter);
                    });
                } else {
                    runOnUiThread(() ->
                            Toast.makeText(MainActivity.this,
                                    "请求失败，响应码: " + response.code(),
                                    Toast.LENGTH_SHORT).show());
                }
            }
        });
    }
}